import { read, utils, writeFile } from "xlsx"
import { addPlayer, editPlayer, getTablePage,delPlayer } from "@/api/playerManage";

export const viewMinix = {
    data() {
        return {
            pageInfo: {
                pageNum: 1,
                pageSize: 10,
                total: 100,
            },
            rowList: [],
            playerMapping: {
                "姓名": "name",
                "年龄": "age",
                "身高": "height",
                "体重": "weight",
                "联系方式": "contactInfo",
                "年级": "grade",
                "班级": "classDesc",
            },
            trainMapping:{
                "训练名称": "trainingName",
                "训练开始时间": "startTime",
                "训练结束时间": "endTime",
                "训练人员": "trainPlayerNames",
                "训练内容": "content",
                "训练地点": "location",
            }
        }
    },
    methods: {
        setSize(v) {
            this.pageInfo.pageNum = 1
            this.pageInfo.pageSize = v
            this.getTableData()
        },
        setPage(v) {
            this.pageInfo.pageNum = v
            this.getTableData()
        },
        handleSearch() {
            this.getTableData()
        },
        fileChange(e) {
            let file = e.target.files[0]
            console.log(file, 'file1111');
            let arrData = []
            file.arrayBuffer().then(res => {
                const wb = read(res)
                const sheet1 = wb.Sheets.Sheet1
                console.log(sheet1, 'sheet1');
                const data = utils.sheet_to_json(sheet1)
                if (this.viewName == 'playerManage') {
                    const mappedData = data.map(row => {
                        return Object.keys(row).reduce((newObj, excelKey) => {
                            if (this.playerMapping[excelKey]) {
                                newObj[this.playerMapping[excelKey]] = row[excelKey];
                            } else {
                                newObj[excelKey] = row[excelKey]; // 如果没有映射关系，保持原键名
                            }
                            return newObj;
                        }, {});
                    });
                    arrData = mappedData
                    // 批量加入数据
                    let promiseArr = []
                    for (let i = 0; i < mappedData.length; i++) {
                        promiseArr.push(addPlayer(mappedData[i]))
                    }
                    Promise.all(promiseArr).then((res) => {
                        this.$message.success('导入成功！')
                        this.getTableData()
                    })
                    this.$refs.fileRef.value = ''
                }
            })
        },
        handleExport() {
            if (this.rowList.length == 0) {
                this.$message.error('请先勾选数据！')
                return
            }
            let mappedData = null
            if (this.viewName == 'playerManage') {
                mappedData = this.rowList.map(row => {
                    return Object.keys(row).reduce((newObj, key) => {
                        // 遍历原始数据的键，并根据映射关系替换
                        const mappedKey = Object.keys(this.playerMapping).find(k => this.playerMapping[k] === key);
                        if (mappedKey) {
                            newObj[mappedKey] = row[key]; // 替换键名
                        } else {
                            // newObj[key] = row[key]; // 保留原键名（id 和 joinTime 不变）
                        }
                        return newObj;
                    }, {});
                });
            }else if(this.viewName == 'trainManage'){
                mappedData = this.rowList.map(row => {
                    return Object.keys(row).reduce((newObj, key) => {
                        // 遍历原始数据的键，并根据映射关系替换
                        const mappedKey = Object.keys(this.trainMapping).find(k => this.trainMapping[k] === key);
                        if (mappedKey) {
                            newObj[mappedKey] = row[key]; // 替换键名
                        } else {
                            // newObj[key] = row[key]; // 保留原键名（id 和 joinTime 不变）
                        }
                        return newObj;
                    }, {});
                });
            }else if(this.viewName == 'permissionManage'){
                
            }
            console.log(mappedData, 'mappedData');
            const ws = utils.json_to_sheet(mappedData)
            const wb = utils.book_new()
            utils.book_append_sheet(wb, ws, 'Sheet1')
            if(this.viewName == 'playerManage'){
                writeFile(wb, '球员信息.xlsx')

            }else if(this.viewName == 'trainManage'){
                writeFile(wb, '训练信息.xlsx')
            }
        },
        handleImport() {
            console.log(123);
            this.$refs.fileRef.click()
        }
    },
}